package com.aspire.curator.api;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.framework.recipes.locks.InterProcessReadWriteLock;
import org.apache.curator.retry.RetryNTimes;

/**
 * Curator客户端框架 事务测试
 *
 * @author JustryDeng
 * @date 2018/11/22 17:24
 */
public class LockDemo {

    /**
     * 每3秒重连一次 移动重连3次
     */
    private static RetryPolicy retryPolicy = new RetryNTimes(3, 1000);

    public static void main(String[] args) throws Exception {

        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                //会话超时时间
                .sessionTimeoutMs(5000)
                //重连机制 超时之后 3秒进行一次重连
                .retryPolicy(retryPolicy)
                //命名空间
                .namespace("create")
                .build();
        // 启动客户端
        client.start();


        //排他锁
        InterProcessMutex interProcessMutex = new InterProcessMutex(client, "/lock1");
        System.out.println("等待获取锁");
        //获取锁
        interProcessMutex.acquire();
        System.out.println(Thread.currentThread().getName() + "准备执行");
        Thread.sleep(5000);
        System.out.println(Thread.currentThread().getName() + "完成执行");
        System.out.println("等待释放锁");
        interProcessMutex.release();


        //读写锁
        InterProcessReadWriteLock interProcessReadWriteLock = new InterProcessReadWriteLock(client, "/lock2");
        //获取读锁对象  读数据时候可以并行
        InterProcessMutex interProcessMutex1 = interProcessReadWriteLock.readLock();

        //获取写锁对象
        InterProcessMutex interProcessMutex2 = interProcessReadWriteLock.writeLock();

        System.out.println("over");
    }



}